package com.miao.activity.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.miao.activity.conifg.IdWorker;
import com.miao.activity.entity.MiaoActivityEntity;
import com.miao.activity.filter.UserFilter;
import com.miao.activity.vo.GOVo;
import com.miao.commonn.vo.GoodsVo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.miao.activity.entity.OrderInfoEntity;
import com.miao.activity.service.OrderInfoService;
import com.miao.commonn.utils.PageUtils;
import com.miao.commonn.utils.R;



/**
 * 
 *
 * @author xk
 * @email 2337156522@QQ.com
 * @date 2022-02-22 16:35:05
 */
@RestController
@RequestMapping("activity/orderinfo")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private UserFilter userFilter;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderInfoService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{oid}")
    public R info(@PathVariable("oid") Integer oid){
		OrderInfoEntity orderInfo = orderInfoService.getById(oid);

        return R.ok().put("orderInfo", orderInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @Transactional
    public R save(@RequestBody MiaoActivityEntity miaoActivityEntity){





        RLock lock = redissonClient.getLock("lock");
        try {
            lock.lock();
        OrderInfoEntity orderInfoEntity = new OrderInfoEntity();
        //获取雪花算法的id
        Long l = idWorker.nextId();
        orderInfoEntity.setOid(l);
        orderInfoEntity.setCreateDate(new Date());
        orderInfoEntity.setMiaoId(miaoActivityEntity.getMiaoId());
        orderInfoEntity.setUserId(miaoActivityEntity.getUserId());
        orderInfoEntity.setDeliveryAddrId(0);
        orderInfoEntity.setShiPrice(miaoActivityEntity.getGoodsPrice());
        orderInfoEntity.setGoodsCount(miaoActivityEntity.getCount());
        orderInfoEntity.setGoodsChannel(0);
        //查询数据库商品
            BoundHashOperations goods_list = redisTemplate.boundHashOps("goods_list");
            GoodsVo goodsVo = (GoodsVo) goods_list.get(miaoActivityEntity.getGoodsId());
        orderInfoEntity.setGoodsName(goodsVo.getGoodsName());
        orderInfoEntity.setStatus(0);
        orderInfoEntity.setPayDate(null);
        orderInfoEntity.setGoodsId(miaoActivityEntity.getGoodsId());
            orderInfoEntity.setGoodsPrice(goodsVo.getGoodsPrice());
        //查询订单 是否有重复
            BoundHashOperations order_list = redisTemplate.boundHashOps("order_list");
            List<OrderInfoEntity> list = (List<OrderInfoEntity>) order_list.get(miaoActivityEntity.getUserId() + "" + miaoActivityEntity.getMiaoId());
            Boolean aBoolean = aBoolean(miaoActivityEntity.getMiaoId(), miaoActivityEntity.getUserId());
            BoundHashOperations activity_list = redisTemplate.boundHashOps("activity_list");
            MiaoActivityEntity miaoActivityEntity1 = (MiaoActivityEntity) activity_list.get(miaoActivityEntity.getMiaoId());
            //订单无重复
            if (aBoolean==true) {
                System.out.println("占坑成功");
                //库存>要购买的库存
                if (goodsVo.getGoodsStock() >= miaoActivityEntity.getCount()) {
                    goodsVo.setGoodsStock(goodsVo.getGoodsStock() - miaoActivityEntity.getCount());
                    //防止数据库超卖判断是否为零
                    GOVo goVo = new GOVo();
                    goVo.setGoodsVo(goodsVo);
                    goVo.setOrderInfoEntity(orderInfoEntity);
                    rabbitTemplate.convertAndSend("aaa","aaa.key",JSON.toJSONString(goVo));
                    return R.ok();
                }
            }else {
                return R.error("您已经添加过订单");
            }
        }finally {
            lock.unlock();
        }
      return R.error("库存不足");
    }

    public Boolean aBoolean(Integer miao,Integer user){

        BoundHashOperations order_list = redisTemplate.boundHashOps("order_list");

        List<OrderInfoEntity> values = order_list.values();

        for (OrderInfoEntity value : values) {
            System.out.println(value.getMiaoId()+""+value.getUserId());
            if (value.getUserId().toString().equals(user.toString())&&value.getMiaoId().toString().equals(miao.toString())){
                return false;
            }

        }
        return true;
    }
    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody OrderInfoEntity orderInfo){
		orderInfoService.updateById(orderInfo);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] oids){
		orderInfoService.removeByIds(Arrays.asList(oids));

        return R.ok();
    }

}
